package priv.xp.androidexample

import android.Manifest
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.view.MenuItem
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.bottomnavigation.BottomNavigationView
import priv.xp.androidexample.databinding.ActivityMainBinding
import pub.devrel.easypermissions.EasyPermissions

@Route(path = "/main/activity")
class MainActivity : AppCompatActivity(), BottomNavigationView.OnNavigationItemSelectedListener {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.navBottom.setOnNavigationItemSelectedListener(this)

        supportFragmentManager.beginTransaction()
            .add(R.id.mainFrame, ARouter.getInstance().build("/camera/fragment").navigation() as Fragment)
            .commit()

        if (!EasyPermissions.hasPermissions(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
            )
        ) {
            EasyPermissions.requestPermissions(
                this, "需要请求您的设想头和写文件权限", 0,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
            )
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        return  when (item.itemId) {
            R.id.navPhoto -> {
                supportFragmentManager.beginTransaction()
                    .replace(R.id.mainFrame, ARouter.getInstance().build("/camera/fragment").navigation() as Fragment)
                    .commit()
                return true
            }
            R.id.navGirl -> {
                supportFragmentManager.beginTransaction()
                    .replace(R.id.mainFrame, ARouter.getInstance().build("/girl/fragment").navigation() as Fragment)
                    .commit()
                return true
            }
            R.id.navQRCode -> {
                supportFragmentManager.beginTransaction()
                    .replace(R.id.mainFrame, ARouter.getInstance().build("/qrcode/fragment").navigation() as Fragment)
                    .commit()
                return true
            }
            else -> false
        }
    }
}
